package com.fashiontextile.user.controller;

import com.fashiontextile.common.constant.TokenConstants;
import com.fashiontextile.common.entity.R;
import com.fashiontextile.user.entity.Article;
import com.fashiontextile.user.entity.Comment;
import com.fashiontextile.user.service.ArticleService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/article")
@AllArgsConstructor
public class ArticleController {

    ArticleService articleService;

    @PostMapping("/type/{daid}")
    public R<?> publishArticle(@PathVariable("daid") Long daid, @RequestBody Article article,
                               @RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid) {
        R<?> responseResult = articleService.publishArticle(daid, article, uid);
        if (responseResult == null) {
            return R.fail("文章类别不存在");
        }
        return responseResult;
    }

    @PutMapping("")
    public R<?> modifyArticle(@RequestBody Article article, @RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid) {
        return articleService.upDateArticleByAid(uid, article);
    }

    @DeleteMapping("/id/{aid}")
    public R<?> deleteArticle(@PathVariable("aid") Long aid,
                              @RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid) {
        return articleService.deleteArticle(uid,aid);
    }

    @GetMapping("")
    public R<?> getArticles(String sort, @RequestParam(required = false) Long type,
                            @RequestParam(required = false, defaultValue = "1") Integer page) {
        if ("type".equals(sort) && type != null) {
            return articleService.selectArticles(type, page);
        }
        if ("new".equals(sort) && type == null) {
            return articleService.selectArticles(type, page);
        }
        return R.fail("没有对应类型的文章");
    }

    @GetMapping("/me")
    public R<?> getArticles(@RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid){
        return articleService.getArticleByUid(uid);
    }

    @GetMapping("/id/{aid}")
    public R<?> getArticleByAid(@PathVariable Long aid){
        return articleService.getArticleByAid(aid);
    }

    @PostMapping("/{aid}/comment")
    public R<?> commentArticle(@PathVariable Long aid,
                               @RequestBody Comment comment,
                               @RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid){
        return articleService.insertComment(aid,comment,uid);
    }

    @GetMapping("/{aid}/comment")
    public R<?> showArticleComment(@PathVariable("aid")Long aid){
        return articleService.selectCommentByctid(aid);
    }
}
